package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type SysSubject struct {
	api.Api
}

// GetPage
// @Summary 列表班级信息数据
// @Description 获取JSON
// @Tags 班级
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class [get]
// @Security Bearer
func (e SysSubject) GetPage(c *gin.Context) {
	s := service.SysSubject{}
	req := dto.SysSubjectGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Form).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysSubject, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 创建班级
// @Description 获取JSON
// @Tags 班级
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysCourseInsertReq true "班级数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-course [post]
// @Security Bearer
func (e SysSubject) Insert(c *gin.Context) {
	s := service.SysSubject{}
	req := dto.SysSubjectInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	lastId, err := s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(lastId, "创建成功")
}

// Update
// @Summary 修改班级数据
// @Description 获取JSON
// @Tags 班级
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysUserUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [put]
// @Security Bearer
func (e SysSubject) Update(c *gin.Context) {
	s := service.SysSubject{}
	req := dto.SysSubjectUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除班级数据
// @Description 删除数据
// @Tags 班级
// @Param userId path int true "classId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [delete]
// @Security Bearer
func (e SysSubject) Delete(c *gin.Context) {
	s := service.SysSubject{}
	req := dto.SysSubjectById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//校验科目是否在使用
	for _, id := range req.Ids {
		//获取科目name
		sub := models.SysSubject{}
		e.Orm.Table(sub.TableName()).Where("deleted_at is null and id=?", id).First(&sub)
		if sub.Id == 0 {
			xlog.Error("科目不存在 subject:", id)
			e.Error(500, err, "科目不存在")
			return
		}

		cou := models.SysCourse{}
		e.Orm.Table(cou.TableName()).Where("deleted_at is null and subject=?", sub.Name).First(&cou)
		if cou.CourseId != 0 {
			xlog.Error("科目正在使用 subject:", sub.Name)
			e.Error(500, err, "科目正在使用 不能删除")
			return
		}
		ocou := models.SysOfflineCourse{}
		e.Orm.Table(ocou.TableName()).Where("deleted_at is null and subject=?", sub.Name).First(&ocou)
		if ocou.CourseId != 0 {
			xlog.Error("科目正在使用 subject:", sub.Name)
			e.Error(500, err, "科目正在使用 不能删除")
			return
		}
		mcou := models.SysMaterial{}
		e.Orm.Table(mcou.TableName()).Where("deleted_at is null and subject=?", sub.Name).First(&mcou)
		if mcou.Id != 0 {
			xlog.Error("科目正在使用 subject:", sub.Name)
			e.Error(500, err, "科目正在使用 不能删除")
			return
		}
	}
	// 设置删除人
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

func (e SysSubject) GetSubjectList(c *gin.Context) {
	req := dto.SysSubjectGetListReq{}
	err := e.MakeContext(c).
		MakeOrm().Bind(&req).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var model models.SysSubject
	var list []*SubjectList
	err = e.Orm.Model(&model).Scopes(cDto.MakeCondition(req.GetNeedSearch())).Find(&list).Error
	if err != nil {
		e.Error(200, err, "数据库查询错误")
	}
	e.OK(&list, "OK")
	return
}

type SubjectList struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

func (e SysSubject) CreateKnowledgePoint(c *gin.Context) {
	req := dto.SysKnowledgePointsInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var model models.SysKnowledgePoint
	req.Generate(&model)
	err = e.Orm.Create(&model).Error
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "成功")
	return
}

func (e SysSubject) DeleteKnowledgePoint(c *gin.Context) {
	req := dto.SysKnowledgePointById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var model models.SysKnowledgePoint
	err = e.Orm.Table(model.TableName()).Delete(model, req.Id).Error
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "删除成功")
	return
}

func (e SysSubject) Get(c *gin.Context) {
	s := service.SysSubject{}
	req := dto.SysSubjectById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.SysSubject
	var knowledgePoint models.SysKnowledgePoint
	var list []*models.SysKnowledgePoint
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}

	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	err = e.Orm.Model(knowledgePoint).Where("subject_id = ?", req.Id).Find(&list).Error
	if err != nil {
		xlog.Error(err)
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}
	object.KnowledgePoint = list
	e.OK(object, "查询成功")
}
